import * as UserAPI from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  roles: [],
  mannger: {}
}
const getters = {
  getManngerType: (state) => {
    return state.mannger.type === 'CHANNEL' ? 'none' : 'block'
  }
}
const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_MANNGER: (state, mannger) => {
    state.mannger = mannger
  }
}

const actions = {
  // user login
  loginByUsername({ commit }, userInfo) {
    const { username, password, codeKey, code } = userInfo
    return new Promise((resolve, reject) => {
      UserAPI.loginByUsername(username, password, codeKey, code).then(response => {
        const data = response.data
        if (data.code !== 0) {
          reject(data.msg)
        } else {
          commit('SET_TOKEN', data.data)
          setToken(response.data.data)
          resolve()
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 获取用户信息
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      UserAPI.getManagerInfo().then(response => {
        // 当前的code不为0直接返回
        if (response.data.code !== 0) {
          reject(response.data.msg)
        }
        const data = response.data.data
        // 保存用户信息
        commit('SET_MANNGER', data.manager)
        if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
          const rs = []
          data.roles.map((role) => {
            rs.push(role)
          })
          commit('SET_ROLES', rs)
        } else {
          commit('SET_ROLES', ['anonymous'])
          reject('登陆信息已经失效,请重新登陆')
        }
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      UserAPI.logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        removeToken()
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 前端 登出
  FedLogOut({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  }
}

export default {
  state,
  mutations,
  getters,
  actions
}

